/**
* jet-sdk script
* ======
* @author 洪波
* @version 19.04.03
*/
const CDN_HOST = 'https://zhuamu.oss-cn-beijing.aliyuncs.com/';
/**
 * 网络请求类
 */
const Lets = function () {
    this.xmlHttp = null;
    this.headers = {};
    this.resultType = 'json';
};
Lets.prototype = {
    constructor: Lets,
    get: function (url, resultType, headers) {
        let lets = new Lets();
        if (resultType) {
            this.resultType = resultType;
        }
        if (headers) {
            this.headers = headers;
        }
        return lets.request('GET', url, '', false);
    },
    post: function (url, params, resultType, headers) {
        let paramsStr = '';
        if (params) {
            for (let key in params) {
                paramsStr += '&' + key + '=' + params[key];
            }
        }
        let lets = new Lets();
        if (resultType) {
            this.resultType = resultType;
        }
        if (headers) {
            this.headers = headers;
        }
        return lets.request('POST', url, paramsStr, false);
    },
    upload: function (url, formData, resultType, headers) {
        let lets = new Lets();
        if (resultType) {
            this.resultType = resultType;
        }
        if (headers) {
            this.headers = headers;
        }
        return lets.request('POST', url, formData, true);
    },
    request: function (method, url, data, multipart) {
        this.xmlHttp = new XMLHttpRequest();
        this.xmlHttp.open(method, url, true);
        if (this.headers.length > 0) {
            for (let key in this.headers) {
                this.xmlHttp.setRequestHeader(key, this.headers[key]);
            }
        }
        if (multipart) {
            this.xmlHttp.send(data);
        } else {
            this.xmlHttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
            if (data != '') {
                this.xmlHttp.send(data.substring(1));
            } else {
                this.xmlHttp.send();
            }
        }
        return this;
    },
    then: function (callback) {
        let f = this;
        f.xmlHttp.onreadystatechange = function() {
            if (f.xmlHttp.readyState == 4 && f.xmlHttp.status == 200) {
                if (f.resultType == 'json') {
                    return callback(JSON.parse(f.xmlHttp.responseText));
                } else {
                    return callback(f.xmlHttp.responseText);
                }
            }
        };
    }
}
const lets = new Lets();

/**
 * 格式化时间
 * @param {*} format    y-m-d h:i:s
 * @param {*} time      毫秒时间戳
 * @param {*} timezone  时区 
 */
const dateFormat = function(time, format){
    let date;
    if (time) {
        date = new Date(time);
    } else {
        date = new Date();
    }
    let dateDict = {
        'y': date.getFullYear(),
        'm': date.getMonth() + 1,
        'd': date.getDate(),
        'h': date.getHours(),
        'i': date.getMinutes(),
        's': date.getSeconds()
    };
    if (format == undefined) {
        format = 'y-m-d h:i:s';
    }
    let dateStr = '';
    for(let i=0; i<format.length; i++) {
        let s = format.charAt(i);
        if (dateDict[s]) {
            dateStr += dateDict[s] < 10 ? '0'+dateDict[s] : dateDict[s];
        } else if (dateDict[s] == 0) {
            dateStr += '00';
        } else {
            dateStr += s;
        }
    }
    return dateStr;
};
/**
 * Vue组件 分页视图
 */
const Pagination = {
    data: function(){
        return {
            current: 1,
            size: 5,
            pages: [],
            allPage: 0,
            limit: 10,
            callback: null
        }
    },
    methods: {
        init(limit, size) {
            this.limit = limit || 10;
            this.size = size || 5;
        },
        onPage: function(page){
            this.current = parseInt(page);
            this.render();
            if (this.page != 0 && this.callback != null) {
                this.callback(page);
            }
        },
        setCallback: function(callback){
            this.callback = callback;
        },
        setData: function(allCount, reset) {
            this.allPage = Math.ceil(allCount / this.limit);
            if (this.current > this.allPage || reset == true) {
                this.current = 1;
            }
            this.render();
        },
        render: function(){
            if (this.allPage > 0) {
                let pages = [];
                if (this.current == 1) {
                    let num = 1;
                    let c = 1;
                    while (num <= this.allPage) {
                        pages.push(num);
                        num++;
                        if (++c > this.size) {
                            break;
                        }
                    }
                } else if (this.current == this.allPage) {
                    let num = this.allPage;
                    let c = 1;
                    while (num > 0) {
                        pages.push(num);
                        num--;
                        if (++c > this.size) {
                            break;
                        }
                    }
                    pages = pages.reverse();
                } else {
                    let num = this.current;
                    let c = 1;
                    while (num > 0) {
                        pages.push(num);
                        num--;
                        if (++c > this.size) {
                            break;
                        }
                    }
                    pages = pages.reverse();
                    num = this.current + 1;
                    c = 1;
                    while (num <= this.allPage) {
                        pages.push(num);
                        num++;
                        if (++c > this.size) {
                            break;
                        }
                    }
                }
                this.pages = pages;
            }
        }
    },
    template: '<div class="pagination"><ul v-if="allPage>0"><li v-on:click="onPage(1)"><a href="javascript:;">&lt;</a></li>'
        + '<li v-on:click="onPage(item)" v-bind:class="{active: current==item}" v-for="item in pages"><a href="javascript:;">{{item}}</a></li>'
        + '<li v-on:click="onPage(allPage)"><a href="javascript:;">&gt;</a></li></ul></div>'
};
/** 
 * 日期选择器
*/
const Datepicker = {
    data: function () {
        return {
            value: '',
            showPicker: false,
            year: 0,
            month: 0,
            day: 0,
            header: ['日','一','二','三','四','五','六'],
            endDay: [31,0,31,30,31,30,31,31,30,31,30,31],
            items: [],
            timer: null
        }
    },
    props: ['placeholder', 'value'],
    methods: {
        pickIn: function (c) {
            if (c != '') {
                let m = this.month + 1;
                this.value = this.year + '-' + (m > 9 ? m : '0' + m) + '-' + (c > 9 ? c : '0' + c);
                this.showPicker = false;
                this.$emit('input', this.value);
            } else if (this.timer != null) {
                clearInterval(this.timer);
            }
        },
        show() {
            this.showPicker = true;
            let date;
            if (this.value != '' && /^\d{4}\-\d{2}\-\d{2}$/.test(this.value)) {
                date = new Date(this.value);
            } else {
                date = new Date();
            }
            this.year = date.getFullYear();
            this.month = date.getMonth();
            this.day = date.getDate();
            this.render();
        },
        hide: function () {
            this.timer = setTimeout(() => {
                this.showPicker = false;
                this.timer = null;
                this.$emit('input', this.value);
            }, 500);
        },
        previousM() {
            if (this.timer != null) {
                clearInterval(this.timer);
            }
            if (this.month == 0) {
                this.year--;
                this.month = 11;
            } else {
                this.month--;
            }
            this.render();
        },
        previousY() {
            if (this.timer != null) {
                clearInterval(this.timer);
            }
            this.year--;
            this.render();
        },
        nextM() {
            if (this.timer != null) {
                clearInterval(this.timer);
            }
            if (this.month == 11) {
                this.year++;
                this.month = 0
            } else {
                this.month++;
            }
            this.render();
        },
        nextY() {
            if (this.timer != null) {
                clearInterval(this.timer);
            }
            this.year++;
            this.render();
        },
        cancel() {
            this.value = '';
            this.$emit('input', this.value);
            this.showPicker = false;
        },
        render() {
            let endDay = this.endDay[this.month];
            //判断闰年
            if (endDay == 0) {
                if((this.year % 4 == 0 && this.year % 100 != 0) || (this.year % 400 == 0)) {
                    endDay = 29;
                } else {
                    endDay = 28;
                }
            }
            let now = new Date();
            now.setFullYear(this.year);
            now.setMonth(this.month);
            now.setDate(1);
            let rows = [];
            let cols = [];
            let s = now.getDay();
            let s1 = s;
            let end = endDay + s;
            for (let i=1; i <= end; i++) {
                if (--s >= 0) {
                    cols.push('');
                } else {
                    cols.push(i - s1);
                }
                if (i % 7 == 0) {
                    rows.push(cols);
                    cols = [];
                }
            }
            if (cols.length > 0) {
                rows.push(cols);
            }
            this.items = rows;
        }
    },
    template: '<div class="datepicker"><input type="text" :placeholder="placeholder" @focus="show" @blur="hide" v-model="value"><div class="picker-panel" v-show="showPicker">'
        + '<div class="pure-g"><div class="pure-u-1-3" style="text-align:left;"><a href="javascript:;" @click="previousY"><<</a> <a href="javascript:;" @click="previousM"><</a></div>'
        + '<div class="pure-u-1-3" style="text-align:center"><b>{{year}}年{{month+1}}月</b></div><div class="pure-u-1-3" style="text-align:right"><a href="javascript:;" @click="nextM">></a> <a href="javascript:;" @click="nextY">>></a></div></div>'
        + '<table><tr><th v-for="h in header">{{h}}</th></tr><tr v-for="r in this.items"><td v-for="c in r" @click="pickIn(c)">{{c}}</td></tr></table><button type="button" class="pure-button pure-input-1" @click="cancel">取消</button></div></div>'
};
const InputSearch = {
    data: function () {
        return {
            value: '',
            clazz: '',
            disabled: '',
            refresh: true,
            searchCallback: null,
            dataList: {},
            hasResult: false
        }
    },
    props: ['placeholder', 'clazz', 'disabled'],
    watch: {
        value: function (val) {
            if (val == undefined)
                return;
            if (this.refresh) {
                this.loadList(val);
            }
            this.refresh = true;
        },
    },
    methods: {
        setText: function (name) {
            this.refresh = false;
            this.value = name;
        },
        selected: function (id, name) {
            this.refresh = false;
            this.value = name;
            this.dataList = null;
            this.$emit('input', id);
            this.$emit('change', id);
            this.hasResult = false;
        },
        focus: function() {
            if (this.value == '') {
                this.loadList('');
            }
        },
        blur: function () {
            setTimeout(() => {
                if (this.value == '') {
                    this.dataList = null;
                    this.hasResult = false;
                }
            }, 200);
        },
        cancel: function () {
            this.selected('', '');
        },
        setSearchCallback: function (callback) {
            this.searchCallback = callback;
        },
        loadList: function (val) {
            if (this.searchCallback != null) {
                this.searchCallback(val, data => {
                    this.dataList = data;
                    let dsr = JSON.stringify(data);
                    if (dsr != '{}' && dsr != '[]') {
                        this.hasResult = true;
                    } else {
                        this.hasResult = false;
                    }
                });
            }
        }
    },
    template: '<div class="input-search" :class="clazz"><input type="text" :placeholder="placeholder" :disabled="disabled" v-model="value" @focus="focus" @blur="blur" />'
        +'<img src="/images/i-x.png" v-show="value" @click="cancel" v-if="!disabled" />'
        +'<div class="input-search-panel" v-show="hasResult"><div class="input-search-item" v-for="(opt,i) in dataList" @click="selected(i,opt)">{{opt}}</div><div class="input-search-item-btn" @click="cancel">取消</div></div></div>'
};
/**
 * 面包屑导航
 */
const Breadcrumb = {
    data: function () {
        return {
            rootId: '',
            rootName: '根目录',
            items: [],
            size: 0,
            callback: null
        }
    },
    methods: {
        init (rootId, rootName) {
            this.rootId = rootId || '';
            this.rootName = rootName || '根目录';
        },
        setCallback (callback) {
            this.callback = callback;
        },
        push (id, name) {
            if (this.items.length == 0) {
                this.items = [{id: this.rootId, name: this.rootName}];
            }
            this.items.push({id: id, name: name});
            this.size = this.items.length;
        },
        cut (index) {
            if (index == this.size - 1) {
                return;
            }
            if (index > 0) {
                let item = this.items[index];
                if (this.callback != null) {
                    this.callback(item.id);
                }
                let items = this.items;
                items.splice(index+1);
                this.items = items;
            } else {
                this.items = [];
                this.callback(this.rootId);
            }
            this.size = this.items.length;
        }
    },
    template: '<div class="breadcrumb"><ul><li v-for="(item, i) in items">'
        +'<span v-if="i!=0"> &gt </span><a href="javascript:;" v-on:click="cut(i)" v-bind:class="{last:i==size-1}">{{item.name}}</a></li></ul></div>'
};
/**
 * 判断是否是图片格式
 * @param {*} extName 
 */
const isImage = function(extName) {
    if (['jpg','jpeg','png','bmp'].indexOf(extName) != -1) {
        return true;
    }
    return false;
};
const scoreStar =  function (score) {
    let s = CDN_HOST + '/statics/star-solid.png';
    let e = CDN_HOST + '/statics/star-empty.png';
    let arr = [];
    switch (Math.ceil(score)) {
        case 5:
            arr = [s,s,s,s,s];
            break;
        case 4:
            arr = [s,s,s,s,e];
            break;
        case 3:
            arr = [s,s,s,e,e];
            break;
        case 2:
            arr = [s,s,e,e,e];
            break;
        default:
            arr = [s,e,e,e,e];
    }
    let html = '';
    for (let star of arr) {
        html += '<li><img src="'+star+'" /></li>'
    }
    return html;
};